package com.token;


import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.PermissionResolver;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.logging.Logger;

/**
 *  令牌登录或权限类
 */

@Component
public class LoginRealm extends AuthorizingRealm implements PermissionResolver {

    @Autowired
    private  ShiroPermissionResolver shiroPermissionResolver;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }



    /**
     * 管理权限
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //得登录的用户名
        String username = JwtUtil.getUsername(principals.toString());
        Logger.getLogger("ROOT").info("username:"+username);

        //查数据库，用户的权限，略
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        //把当前登录的用户有哪些权限添加进来，添加哪些，就能访问哪些网址
        this.setPermissionResolver(this);
        authorizationInfo.addObjectPermission(new MyPermission("$/api/"));
        authorizationInfo.addStringPermission("/api/searchDep");

        //authorizationInfo.addStringPermission("/api/removeDepById");
        //authorizationInfo.addStringPermissions();
        return authorizationInfo;
    }

    /**
     * 管理登录  如果有异常，则令牌无效
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //得到客户端传过来的令牌
        String tokenString =(String) token.getPrincipal();
        //根据令牌得用户名,可以查用户库
        String username = JwtUtil.getUsername(tokenString);
        if (username==null)
        {
            throw new RuntimeException("登录失败");
        }

        return new SimpleAuthenticationInfo(tokenString, tokenString, getName());

    }

    @Override
    public Permission resolvePermission(String s) {
        if(s.startsWith("$")){
            return new MyPermission(s);
        }
        return new WildcardPermission(s);
    }
}
